package com.common.wx;

import java.security.MessageDigest;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;
import com.controller.external.PI.EntWeChatMsgController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WechatUtil {
	static final Logger logger = LoggerFactory.getLogger(WechatUtil.class);
	// 海科
//	public static int AGENTID = 1000053;
//	private static String appId = "wx1a8f3deaac701eda";
//	private static String appSecret = "OKEnIO0Y-Y6Q9uScgNFwOqRjSKmkwR4ww42ml6MMjGA";
	// 新源
//	public static int AGENTID = 1000011;// 工资条应用对应id
	public static int AGENTID = 1000034;// 协同应用对应id
	private static String appId = "ww2dc9894bc40be2c8";// 企业微信对应id
//	private static String appSecret = "MUj-2oBxCNNBkwdhaBSwcFxWdYP6H7JUQ2ze0hJbJ1I";// 工资条对应密钥
	public static String APPSECRET = "mp5ftzUDRmOxpR55GMftzhxq9irKVTpbCbJdvxBefhw";// cmp对应密钥

	public static JSONObject getAccessToken() {
		logger.info("**appSecret:" + APPSECRET);
		String accessTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s";
		String requestUrl = String.format(accessTokenUrl, appId, APPSECRET);
		logger.debug("requestUrl:" + requestUrl);
		return WebUtil.doGet(requestUrl);
	}

	// 后面还有部分代码
	// 接上面的access_token获取代码

	public static Map<String, String> generateWxTicket(String jsApiTicket, String url) {
		Map<String, String> ret = new HashMap<>();
		String nonceStr = createNonceStr();
		String timestamp = createTimestamp();
		String string1;
		String signature = "";

		string1 = "jsapi_ticket=" + jsApiTicket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url;

		logger.debug("string1 ====> " + string1);

		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(string1.getBytes("UTF-8"));
			signature = byteToHex(crypt.digest());
			logger.debug("signature ====> " + signature);
		} catch (Exception e) {
			e.printStackTrace();
		}

		ret.put("url", url);
		ret.put("jsapi_ticket", jsApiTicket);
		ret.put("nonceStr", nonceStr);
		ret.put("timestamp", timestamp);
		ret.put("signature", signature);
		ret.put("appid", appId);

		return ret;
	}

	/**
	 * 字节数组转换为十六进制字符串
	 *
	 * @param hash 字节数组
	 * @return 十六进制字符串
	 */
	private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}

	/**
	 * 生成随机字符串
	 *
	 * @return 随机字符串
	 */
	private static String createNonceStr() {
		return UUID.randomUUID().toString();
	}

	/**
	 * 生成时间戳
	 *
	 * @return 时间戳
	 */
	private static String createTimestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}
}